/**
 * <p>Copyright: Copyright (c) 2012</p>
 * <p>Company: 联动优势科技有限公司</p>
 * <p>Apr 20, 2013 3:19:34 PM</p>
 * @author Ding Zhe
 * @version 1.0
 */
package com.umpay.privi.ejb.sys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.umpay.common.persist.ibatis.DataAccessException;
import com.umpay.privi.common.BeanManager;
import com.umpay.privi.common.Constants;
import com.umpay.privi.common.ReqMessage;
import com.umpay.privi.common.ResMessage;
import com.umpay.privi.common.RetCode;
import com.umpay.privi.common.XmlData;
import com.umpay.privi.dao.on.sys.MenuDao;
import com.umpay.privi.dao.on.sys.UserDao;
import com.umpay.privi.helper.ReqParaCheckHelper;
import com.umpay.privi.model.sys.Menu;
import com.umpay.privi.model.sys.User;
import com.umpay.privi.service.sys.MenuServiceRemote;
import com.umpay.privi.util.SeqUtil;
import com.umpay.privi.util.StringUtil;

/** 
 * <p>菜单EJB</p>
 * @author Ding Zhe, May 23, 2013
 * @version 1.0
 */
@TransactionManagement(TransactionManagementType.BEAN)
public class MenuServiceBean implements MenuServiceRemote{
	
	private static Logger logger = LoggerFactory.getLogger(MenuServiceBean.class);

	public ResMessage queryAllSysMenus(ReqMessage req) {
		logger.info(String.format("[MenuServiceBean]queryAllSysMenus请求数据：", req));//TODO 后续应该改为拦截器打印输入输出日志
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(req, "MenuServiceBean.queryAllSysMenus.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		ResMessage res = new ResMessage();//创建报文返回对象
		try {
			MenuDao menuDao = BeanManager.getBean("menuDao", MenuDao.class);
			//请求参数中系统编号为必传
			List<Menu> menus = menuDao.findMenus(req.getReqMap());
			res.put(XmlData.RESULT_LIST, menus);
			res.setRetCode(RetCode.SUCCESS);
			res.setRetMsg("成功");
		} catch (DataAccessException e) {//TODO 后续应该改为拦截器处理非业务异常
			logger.error(e.getMessage(),e);
			res.setRetCode(RetCode.DB_ERROR);
			res.setRetMsg("数据库出错");
		} catch (Exception e) {//TODO 后续应该改为拦截器处理非业务异常
			logger.error(e.getMessage(),e);
			res.setRetCode(RetCode.UNKNOWN);
			res.setRetMsg("未知错误");
		}
		logger.info(String.format("[MenuServiceBean]queryAllSysMenus响应数据：",res));//TODO 后续应该改为拦截器打印输入输出日志
		return res;
	}

	public ResMessage queryNextLevelMenus(ReqMessage req) {
		logger.info("[MenuServiceBean]queryNextLevelMenus请求数据："+req);//TODO 后续应该改为拦截器打印输入输出日志
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(req, "MenuServiceBean.queryNextLevelMenus.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		ResMessage res = new ResMessage();//创建报文返回对象
		try {
			MenuDao menuDao = BeanManager.getBean("menuDao", MenuDao.class);
			//请求参数中系统编号和parentId为必传
			List<Menu> menus = menuDao.findMenus(req.getReqMap());
			res.put(XmlData.RESULT_LIST, menus);
			res.setRetCode(RetCode.SUCCESS);
			res.setRetMsg("成功");
		} catch (DataAccessException e) {//TODO 后续应该改为拦截器处理非业务异常
			logger.error(e.getMessage(),e);
			res.setRetCode(RetCode.DB_ERROR);
			res.setRetMsg("数据库出错");
		} catch (Exception e) {//TODO 后续应该改为拦截器处理非业务异常
			logger.error(e.getMessage(),e);
			res.setRetCode(RetCode.UNKNOWN);
			res.setRetMsg("未知错误");
		}
		logger.info(String.format("[MenuServiceBean]queryNextLevelMenus响应数据：",res));//TODO 后续应该改为拦截器打印输入输出日志
		return res;
	}

	public ResMessage queryMenusByUserId(ReqMessage reqMessage) {
		logger.info("[MenuServiceBean]queryMenusByUserId请求数据："+reqMessage);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(reqMessage, "MenuServiceBean.queryMenusByUserId.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		UserDao userDao = BeanManager.getBean("userDao",UserDao.class);
		
		ResMessage resMessage = new ResMessage();//创建报文返回对象
		try {
			String sysId = reqMessage.getString(XmlData.SYSID);
			String userId = reqMessage.getString(XmlData.USERID);
			User user = userDao.get(userId);
			if(user==null || !sysId.equals(user.getSysId().toString())){
				resMessage.setRetCode(RetCode.NO_DATA);
				resMessage.setRetMsg("用户不存在或不属于本系统");
				logger.info("[MenuServiceBean]queryMenusByUserId响应数据："+resMessage);
				return resMessage;
			}
			List<Integer> menus = userDao.findMenusByUserId(userId);//查询用户菜单
			resMessage.put("menuList", menus);
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("成功");
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		logger.info("[MenuServiceBean]queryMenusByUserId响应数据："+resMessage);
		return resMessage;
	}

	public ResMessage addMenu(ReqMessage req) {
		logger.info("[MenuServiceBean]addMenu请求数据："+req);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(req, "MenuServiceBean.addMenu.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		ResMessage resMessage = new ResMessage();
		try {
			MenuDao menuDao = BeanManager.getBean("menuDao", MenuDao.class);
			int menuId = SeqUtil.genSequence(Constants.MENU_SEQ)+1000;
			Menu menu = new Menu();
			menu.setMenuId(menuId);
			menu.setDescription(StringUtil.trim(req.get(XmlData.DESCRIPTION)));
			menu.setMenuUrl(StringUtil.trim(req.get(XmlData.MENUURL)));
			menu.setModUser(StringUtil.trim(req.get(XmlData.MODUSER)));
			menu.setSysId(Short.parseShort(StringUtil.trim(req.get(XmlData.SYSID))));
			menu.setMenuName(StringUtil.trim(req.get(XmlData.MENU_NAME)));
			menu.setParentId(Integer.parseInt(StringUtil.trim(req.get(XmlData.PARENTID))));
			menu.setDeep(Short.parseShort(StringUtil.trim(req.get(XmlData.DEEP))));
			menu.setFlag(Short.parseShort(StringUtil.trim(req.get(XmlData.FLAG))));
			menu.setSort(Short.parseShort(StringUtil.trim(req.get(XmlData.SORT))));
			menuDao.insert(menu);
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("成功");
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		return resMessage;
	}

	public ResMessage modfiyMenu(ReqMessage req) {
		logger.info("[MenuServiceBean]modfiyMenu请求数据："+req);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(req, "MenuServiceBean.modfiyMenu.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		ResMessage resMessage = new ResMessage();
		try {
			Menu menu = new Menu();
			menu.setMenuId(Integer.parseInt(StringUtil.trim(req.get(XmlData.MENUID))));
			menu.setDescription(StringUtil.trim(req.get(XmlData.DESCRIPTION)));
			menu.setMenuUrl(StringUtil.trim(req.get(XmlData.MENUURL)));
			menu.setModUser(StringUtil.trim(req.get(XmlData.MODUSER)));
			menu.setSysId(Short.parseShort(StringUtil.trim(req.get(XmlData.SYSID))));
			menu.setMenuName(StringUtil.trim(req.get(XmlData.MENU_NAME)));
			if(StringUtil.isNotEmpty(StringUtil.trim(req.get(XmlData.PARENTID))))
			menu.setParentId(Integer.parseInt(StringUtil.trim(req.get(XmlData.PARENTID))));
			if(StringUtil.isNotEmpty(StringUtil.trim(req.get(XmlData.DEEP))))
			menu.setDeep(Short.parseShort(StringUtil.trim(req.get(XmlData.DEEP))));
			if(StringUtil.isNotEmpty(StringUtil.trim(req.get(XmlData.FLAG))))
			menu.setFlag(Short.parseShort(StringUtil.trim(req.get(XmlData.FLAG))));
			
			MenuDao menuDao = BeanManager.getBean("menuDao", MenuDao.class);
			menuDao.update(menu);
			resMessage.setRetCode(RetCode.SUCCESS);
			resMessage.setRetMsg("成功");
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		return resMessage;
	}

	public ResMessage moveMenu(ReqMessage req) {
		logger.info("[MenuServiceBean]moveMenu请求数据："+req);
		//上送数据校验
		ResMessage checkPara = ReqParaCheckHelper.checkRequire(req, "MenuServiceBean.moveMenu.require");
		if (!RetCode.SUCCESS.equals(checkPara.getRetCode())) {
			return checkPara;
		}
		ResMessage resMessage = new ResMessage();
		try {
			MenuDao menuDao = BeanManager.getBean("menuDao", MenuDao.class);
			Map<String,Object> findMap = new HashMap<String,Object>();
			findMap.put(XmlData.PARENTID, StringUtil.trim(req.get(XmlData.PARENTID)));
			List<Menu> listMenu = menuDao.findMenus(findMap);
			if(null!=listMenu&&listMenu.size()>0){
				for(int i=0;i<listMenu.size();i++){
					Menu menu = listMenu.get(i);
					if(menu.getSort()!=i){
						menu.setSort((short)i);
						menuDao.update(menu);
					}
					if(StringUtil.trim(menu.getMenuId()).equals(StringUtil.trim(req.get(XmlData.MENUID)))){
						if(StringUtil.trim(req.get(XmlData.UP_MOVE)).equals("1")){
							logger.info("上移菜单");
							if(i==0){
								continue;
							}
							Menu lastMenu = listMenu.get(i-1);
							lastMenu.setSort((short)i);
							menuDao.update(lastMenu);
							menu.setSort((short)(i-1));
							menuDao.update(menu);
							
						}else if(StringUtil.trim(req.get(XmlData.DOWN_MOVE)).equals("1")){
							logger.info("下移菜单");
							if(i==listMenu.size()-1){
								continue;
							}
							Menu nextMenu = listMenu.get(i+1);
							nextMenu.setSort((short)i);
							menuDao.update(nextMenu);
							menu.setSort((short)(i+1));
							menuDao.update(menu);
							i=i+1;
						}
					}
				}
			}else{
				logger.info("根据父菜单Id查询子菜单结构不存在");
			}
		} catch (DataAccessException e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.DB_ERROR);
			resMessage.setRetMsg("数据库出错");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			resMessage.setRetCode(RetCode.UNKNOWN);
			resMessage.setRetMsg("未知错误");
		}
		return resMessage;
	}
	
}
